package com.company.common.sql.builder;


import com.company.common.utils.MakerwitUtil;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.builder.annotation.ProviderMethodResolver;
import org.apache.ibatis.jdbc.SQL;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class SqlBuilder implements ProviderMethodResolver {

    public static String selectTabNameById(@Param("tabName") String tabName, @Param("id") int id) {
        return new SQL() {
            {
                SELECT("*");
                FROM(tabName);
                if (id != 0)
                    WHERE("id =#{id}");
            }
        }.toString();
    }

    public static String selectTabNameByColumns(@Param("tabName") String tabName, @Param("columns") Map colums) {
        SQL sql = new SQL() {
            {
                SELECT("*");
                FROM(tabName);
                if (colums != null && !colums.isEmpty()) {
                    Iterator entrys = (Iterator) colums.entrySet().iterator();
                    while (entrys.hasNext()) {
                        Map.Entry<String, Object> entery = (Map.Entry) entrys.next();
                        String key = entery.getKey();
                        Object value = entery.getValue();
                        if (value != null && !value.getClass().getSimpleName().equals("HashMap") && !value.equals(""))//非空不是map才符合要求
                        {
                            String remark = value.toString().toLowerCase().trim();//将字符串转变为小写并删除字符串的头尾空白符
                            if (remark.indexOf("like") == 0)//返回第一次出现的索引并判断
                                WHERE(key.concat(" ").concat((MakerwitUtil.trimRight(value.toString().replaceFirst("%", "'%")).concat("'"))));
                                //给定的参数 replacement 替换字符串第一个匹配给定的正则表达式的子字符串
                            else if (remark.indexOf(">") == 0 || remark.indexOf(">=") == 0 || remark.indexOf("<") == 0 || remark.indexOf("<=") == 0)
                                WHERE(key.concat(" ").concat(value.toString()));
                            else if (remark.indexOf("in") == 0)
                                WHERE(key.concat(" ").concat(value.toString()));//将指定的字符串参数连接到字符串上
                            else
                                WHERE(key + " = #{columns." + key + "}");
                        }
                    }
                }
            }
        };
        return sql.toString();
    }

    public static String selectInfoByColumns(@Param("tabName") String tabName, @SuppressWarnings("rawtypes") @Param("columns") Map columns) {
        SQL sql = new SQL() {
            {
                SELECT(" * ");
                FROM(tabName);
                if (columns != null && !columns.isEmpty()) {
                    @SuppressWarnings("rawtypes")
                    Iterator entrys = (Iterator) columns.entrySet().iterator();
                    while (entrys.hasNext()) {
                        @SuppressWarnings({"rawtypes", "unchecked"})
                        Map.Entry<String, Object> entry = (Map.Entry) entrys.next();
                        String key = entry.getKey();
                        Object value = entry.getValue();
//                        if(StringUtils.isNotNull(value)&&!value.getClass().getSimpleName().equals("HashMap")&&!value.equals(""))//非空不是map才符合要求
//                        {
                        if (value != null && !value.getClass().getSimpleName().equals("HashMap") && !value.equals(""))//非空不是map才符合要求
                        {
                            String remark = value.toString().toLowerCase().trim();
                            if (remark.indexOf("like") == 0)
                                WHERE(key.concat(" ").concat((MakerwitUtil.trimRight(value.toString().replaceFirst("%", "'%")).concat("'"))));
                            else if (remark.indexOf(">") == 0 || remark.indexOf(">=") == 0 || remark.indexOf("<") == 0 || remark.indexOf("<=") == 0)
                                WHERE(key.concat(" ").concat(value.toString()));
                            else if (remark.indexOf("in") == 0)
                                WHERE(key.concat(" ").concat(value.toString()));
                            else
                                WHERE(key + " = #{columns." + key + "}");
                        }
                    }
                }
            }
        };
        return sql.toString();
    }

    public static String selectInfoByColumnsOrderby(@Param("tabName") String tabName, @SuppressWarnings("rawtypes") @Param("columns") Map columns, @Param("orderby") String orderby) {
        SQL sql = new SQL() {
            {
                SELECT(" * ");
                FROM(tabName);
                if (columns != null && !columns.isEmpty()) {
                    @SuppressWarnings("rawtypes")
                    Iterator entrys = (Iterator) columns.entrySet().iterator();
                    while (entrys.hasNext()) {
                        @SuppressWarnings({"rawtypes", "unchecked"})
                        Map.Entry<String, Object> entry = (Map.Entry) entrys.next();
                        String key = entry.getKey();
                        Object value = entry.getValue();
                        if (value != null && !value.getClass().getSimpleName().equals("HashMap") && !value.equals(""))//非空不是map才符合要求
                        {
                            String remark = value.toString().toLowerCase().trim();
                            if (remark.indexOf("like") == 0)
                                WHERE(key.concat(" ").concat((MakerwitUtil.trimRight(value.toString().replaceFirst("%", "'%")).concat("'"))));
                            else if (remark.indexOf(">") == 0 || remark.indexOf(">=") == 0 || remark.indexOf("<") == 0 || remark.indexOf("<=") == 0)
                                WHERE(key.concat(" ").concat(value.toString()));
                            else if (remark.indexOf("in") == 0)
                                WHERE(key.concat(" ").concat(value.toString()));
                            else
                                WHERE(key + " = #{columns." + key + "}");
                        }
                    }
                }
                if (!orderby.equals("") && orderby != null) {
                    ORDER_BY(orderby);
                }
            }
        };
        return sql.toString();
    }

    public static String updateTabBySetWhereMap(@Param("tabName") String tabName, @Param("set") Map set, @Param("where") Map where) {
        SQL sql = new SQL() {
            {
                UPDATE(tabName);
                if (set != null && !set.isEmpty()) {
                    Iterator entrys = set.entrySet().iterator();
                    while (entrys.hasNext()) {
                        Map.Entry<String, Object> entry = (Map.Entry) entrys.next();
                        String key = entry.getKey();
                        Object value = entry.getValue();
                        if (value != null && !value.getClass().getSimpleName().equals("HashMap"))//非空不是map才符合要求
                        {
                            SET(key + " = #{set." + key + "}");
                        }
                    }
                }
                if (where != null && !where.isEmpty()) {
                    @SuppressWarnings("rawtypes")
                    Iterator entrys = (Iterator) where.entrySet().iterator();
                    while (entrys.hasNext()) {
                        @SuppressWarnings({"rawtypes", "unchecked"})
                        Map.Entry<String, Object> entry = (Map.Entry) entrys.next();
                        String key = entry.getKey();
                        Object value = entry.getValue();
                        if (value != null && !value.getClass().getSimpleName().equals("HashMap"))//非空不是map才符合要求
                        {
                            WHERE(key + " = #{where." + key + "}");
                        }
                    }
                }
            }
        };
        return sql.toString();
    }

    public static String deleteTabByWhereMap(@Param("tabName") String tabName, @SuppressWarnings("rawtypes") @Param("where") Map where) {
        SQL sql = new SQL() {
            {
                DELETE_FROM(tabName);
                if (where != null && !where.isEmpty()) {
                    @SuppressWarnings("rawtypes")
                    Iterator entrys = (Iterator) where.entrySet().iterator();
                    while (entrys.hasNext()) {
                        @SuppressWarnings({"rawtypes", "unchecked"})
                        Map.Entry<String, Object> entry = (Map.Entry) entrys.next();
                        String key = entry.getKey();
                        //Object value = entry.getValue();
		                /*if(i==0)
		                {
		                	sbwhere.append(key).append(" = '").append(value).append("'");
		                	i++;
		                	continue;
		                }
		                sbwhere.append(" and ").append(key).append(" = '").append(value).append("'");*/
                        Object value = entry.getValue();
                        if (value != null && !value.getClass().getSimpleName().equals("HashMap"))//非空不是map才符合要求
                        {
                            WHERE(key + " = #{where." + key + "}");//mybatis 可以通过key 找到value值 但是必须用 @Param注解的map 这样可以防止sql 注入
                        }
                    }
                    //WHERE(sbwhere.toString());
                }
            }
        };
        return sql.toString();
    }

    public static String insertTabNameByColumns(@Param("tabName") String tabName, @SuppressWarnings("rawtypes") @Param("columns") Map columns) {
        SQL sql = new SQL() {
            {
                INSERT_INTO(tabName);
                if (columns != null && !columns.isEmpty()) {
                    Iterator entrys = (Iterator) columns.entrySet().iterator();
                    while (entrys.hasNext()) {
                        @SuppressWarnings({"rawtypes", "unchecked"})
                        Map.Entry<String, Object> entry = (Map.Entry) entrys.next();
                        String key = entry.getKey();
                        Object value = entry.getValue();
                        if (value != null && !value.getClass().getSimpleName().equals("HashMap"))//非空不是map才符合要求
                        {
                            INTO_COLUMNS(key);
                            INTO_VALUES("#{columns." + key + "}");
                        }
                    }
                }
            }
        };
        return sql.toString();
    }

    public static String insertBatchAll(@Param("tabName") String tabName, @Param("list") List<Map> list, @Param("flag") boolean flag) {
        SQL sql = new SQL() {
            {
                INSERT_INTO(tabName);
                for (int i = 0; i < list.size(); i++) {
                    Map columns = list.get(i);
                    if (columns != null && !columns.isEmpty()) {
                        Iterator entrys = (Iterator) columns.entrySet().iterator();
                        while (entrys.hasNext()) {
                            @SuppressWarnings({"unchecked"})
                            Map.Entry<String, Object> entry = (Map.Entry) entrys.next();
                            String key = entry.getKey();
                            Object value = entry.getValue();
                            if (flag) {
                                if (i == 0) {
                                    INTO_COLUMNS(key);
                                    INTO_VALUES("#{list".concat("[").concat(i + "").concat("].") + key + "}");
                                } else {
                                    if (value != null && !value.getClass().getSimpleName().equals("HashMap"))//非空不是map才符合要求
                                    {
                                        if (i == 0)
                                            INTO_COLUMNS(key);
                                        INTO_VALUES("#{list".concat("[").concat(i + "").concat("].") + key + "}");
                                    }
                                }
                            }
                            ADD_ROW();
                        }
                    }
                }
            }
        };
        return sql.toString();
    }
}
